<?php

namespace laytp\controller;

use app\middleware\api\ApiLog;
use app\service\api\AuthServiceFacade;
use app\service\api\CheckSignServiceFacade;
use laytp\BaseController;
use laytp\traits\JsonReturn;
use think\facade\Cache;

/**
 * Api应用控制器基类
 * @package laytp\controller
 */
class Api extends BaseController
{
    /**
     * 无需登录的方法,同时也就不需要鉴权了
     * @var array
     */
    protected $noNeedLogin = [];

    /**
     * 无需验证签名的方法
     * @var array
     */
    protected $noNeedCheckSign = [];

    /**
     * 中间件
     * @var array
     */
    protected $middleware = [
        ApiLog::class,
    ];

    protected function initialize()
    {
        //将无需登录的方法名数组设置到权限服务中，以方便中间件获取
        //AuthServiceFacade::setNoNeedLogin($this->noNeedLogin);
        //将无需验证签名的方法名数组设置到Api验证签名服务中，以方便中间件获取
        //CheckSignServiceFacade::setNoNeedCheckSign($this->noNeedCheckSign);
        $this->_initialize();
    }

    // 初始化
    protected function _initialize()
    {
    }


    /**
     * 生成查询条件
     * @param $keys
     * @return array
     */
    public function buildSearchParams($keys)
    {
        $where       = [];
        //传递了search_param就说明是进行搜索查询
        $searchParam = input('post.');
        if (!empty($keys)) {
            foreach ($keys as $field) {
                if ($searchParam[$field] !== '' && isset($searchParam[$field])) {
                    $where[] = [$field, '=', $searchParam[$field]];
                }
            }
        }
        return $where;
    }



    /**
     * 图片路径相对转绝对
     * @param string $img
     * @return string
     */
    public function imgUrlToAbsolute($img = '')
    {
        if (stripos($img, 'http') === false) {
            return $this->getDomain() . $img;
        } else {
            return $img;
        }
    }


    /**
     * 获取当前的网址加目录信息    2017-10-15
     */
    public function getDomain()
    {
        $base = request()->root();
        $root = strpos($base, '.') ? ltrim(dirname($base), DS) : $base;
        if ('' != $root) {
            $root = '/' . ltrim($root, '/');
        }
        if (!input('?server.REQUEST_SCHEME')) {
            $protocol = input('server.SERVER_PORT') == 443 ? "https" : "http";
        } else {
            $protocol = input('server.REQUEST_SCHEME');
        }
        return $protocol . '://' . input('server.HTTP_HOST') . $root;
    }

    public function clearCache(){
        Cache::clear();
    }
}